package personal.emailsender.server.service.dispatcher;

import java.util.logging.Logger;

import personal.emailsender.server.service.EmailSendService;
import personal.emailsender.server.service.impl.MailGunSendingServiceImpl;
import personal.emailsender.server.service.impl.MandrillSendingServiceImpl;
import personal.emailsender.shared.data.EmailContent;
import personal.emailsender.shared.data.ServerResponse;
import personal.emailsender.shared.util.HtmlUtil;
import personal.emailsender.shared.verifier.EmailContentFieldVerifier;

public class EmailSendingDispatcherUtil {

	private static final Logger logger = Logger
			.getLogger(MailGunSendingServiceImpl.class.getSimpleName());
	private static final EmailSendService MANDRILL_SERVICE = new MandrillSendingServiceImpl();
	private static final EmailSendService MAILGUN_SERVICE = new MailGunSendingServiceImpl();

	private EmailSendingDispatcherUtil() {
	}

	public static ServerResponse sendEmail(EmailContent emailContent) {
		logger.warning("Started verifier");
		try {
			EmailContentFieldVerifier.verify(emailContent);
			emailContent.setSubject(HtmlUtil.escapeHtml(emailContent.getSubject()));
			emailContent.setContent(HtmlUtil.scrubber(emailContent.getContent()));
		} catch (Exception e) {
			logger.warning("warning from verifier: " + e.getMessage());
			return new ServerResponse(false, e.getMessage());
		}

		logger.warning("Start sending: " + emailContent);
		try {
			if (MANDRILL_SERVICE.sendEmail(emailContent)) {
				return new ServerResponse(true, "Success!");
			}
		} catch (Exception e) {
			logger.warning(e.getMessage());
		}

		// fallback to secondary service
		try {
			if (MAILGUN_SERVICE.sendEmail(emailContent)) {
				return new ServerResponse(true, "Success!");
			}
		} catch (Exception e) {
			logger.warning(e.getMessage());
		}

		return new ServerResponse(false, "Failed with unknown reason, sorry!");
	}
}
